package com.gaswell.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaswell.entity.Qba01;
import com.gaswell.entity.Qba01M;
import com.gaswell.entity.Qfc01;
import com.gaswell.mapper.Qba01MMapper;
import com.gaswell.mapper.RtuDataMapper;
import com.gaswell.pojo.ReciveCycleData;
import com.gaswell.service.*;
import com.gaswell.utils.DateUtils;
import com.gaswell.utils.StatusDetect;
import com.gaswell.vo.Qba01Count;
import com.gaswell.vo.Qba01Params;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

/**
 * <p>
 * 采气井日数据 服务实现类
 * </p>
 *
 * @author Lei Wang
 * @since 2022-05-24
 */
@Service
@DS("mysql")
public class Qba01MServiceImpl extends ServiceImpl<Qba01MMapper, Qba01M> implements IQba01MService {
    @Autowired
    IQfc01Service qfc01Service;
    @Autowired
    IQaa10Service qaa10Service;
    @Autowired
    private RtuDataMapper rtuDataMapper;

    @Autowired
    IQba01Service qba01Service;

    @Autowired
    private DiagnosisNewService diagnosisNewService;
    @Autowired
    private QjService qjService;
    @Autowired
    IQba01Service2 qba01Service2;


    @Override
    @Async("threadPoolTaskExecutor_forqba01")
    public Future<Qba01> getJiYeAndDDThread(Qba01 qba01) {
        double g = 0.6;
        double d = 62;
        double vg = 2.5;
        Timestamp start = DateUtils.stringToDate(DateUtils.sqldateToString(qba01.getRq()) + " 00:00:00");
        Timestamp end = DateUtils.stringToDate(DateUtils.sqldateToString(qba01.getRq()) + " 23:59:59");

        /**
         * 获取天然气相对密度
         */
        QueryWrapper<Qfc01> qfc01QueryWrapper = new QueryWrapper<>();
        qfc01QueryWrapper.eq("JH", qba01.getJh())
                .ge("QYRQ", start)
                .le("QYRQ", end);
        Qfc01 one = qfc01Service.getOne(qfc01QueryWrapper);
        if (one != null && one.getTrqxdmd() != null)
            g = one.getTrqxdmd().doubleValue();


        ReciveCycleData reciveCycleData = new ReciveCycleData()
                .setJkwd(qba01.getJkwd() == null ? 0 : qba01.getJkwd().doubleValue())
                .setTgyl(qba01.getPjty() == null ? 0 : qba01.getPjty().doubleValue())
                .setYgyl(qba01.getPjyy() == null ? 0 : qba01.getPjyy().doubleValue())
                .setWsyl(qba01.getWsyl() == null ? 0 : qba01.getWsyl().doubleValue())
                .setCqill(qba01.getRcql() == null ? 0 : qba01.getRcql().doubleValue());
        String jiYe = StatusDetect.isJiYe(reciveCycleData, g, d, vg);
        String shuiHeWu = StatusDetect.isShuiHeWu(reciveCycleData, g);
        LinkedList<String> strings = new LinkedList<>();
//        strings.add(jiYe);
//        strings.add(shuiHeWu);
        qba01.setJy(jiYe)
                .setDd(shuiHeWu);


        return new AsyncResult<Qba01>(qba01);
    }


    /**
     * 按日期以及多个井号查询日数据巡检情况
     *
     * @param qba01s
     * @param date
     * @return
     */
    @Override
    @Async("threadPoolTaskExecutor_forqba01")
    public CompletableFuture<String> getJiYeAndDDThreadGroupByDate(List<Qba01> qba01s, String date, List<Qba01> result) {

        double g = 0.6;
        double d = 62;
        double vg = 2.5;
        Timestamp start = DateUtils.stringToDate(date + " 00:00:00");
        Timestamp end = DateUtils.stringToDate(date + " 23:59:59");


        HashMap<String, Qba01Params> stringQba01ParamsHashMap = new HashMap<>();

        LinkedList<String> jhs = new LinkedList<>();
        for (Qba01 qba01 : qba01s) {
            jhs.add(qba01.getJh());
        }
        /**
         * 获取天然气相对密度
         */
//        LambdaQueryWrapper<Qfc01> qfc01LambdaQueryWrapper = new LambdaQueryWrapper<>();
//        qfc01LambdaQueryWrapper.in(Qfc01::getJh, jhs)
//                .eq(Qfc01::getQyrq, start)
//                .eq(Qfc01::getQyrq, end);
//        List<Qfc01> qfc01s = qfc01Service.list(qfc01LambdaQueryWrapper);
//
//        for (Qfc01 qfc01 : qfc01s) {
//            if (!stringQba01ParamsHashMap.containsKey(qfc01.getJh()))
//                stringQba01ParamsHashMap.put(qfc01.getJh(), new Qba01Params());
//            Qba01Params qba01Params = stringQba01ParamsHashMap.get(qfc01.getJh());
//            qba01Params.g = qfc01.getTrqxdmd() == null ? qba01Params.g : qfc01.getTrqxdmd().doubleValue();
//            stringQba01ParamsHashMap.replace(qfc01.getJh(), qba01Params);
//        }

        for (Qba01 qba01 : qba01s) {
            ReciveCycleData reciveCycleData = new ReciveCycleData()
                    .setJkwd(qba01.getJkwd() == null ? 0 : qba01.getJkwd().doubleValue())
                    .setTgyl(qba01.getPjty() == null ? 0 : qba01.getPjty().doubleValue())
                    .setYgyl(qba01.getPjyy() == null ? 0 : qba01.getPjyy().doubleValue())
                    .setWsyl(qba01.getWsyl() == null ? 0 : qba01.getWsyl().doubleValue())
                    .setCqill(qba01.getRcql() == null ? 0 : qba01.getRcql().doubleValue());
            String jiYe = StatusDetect.isJiYe(reciveCycleData, g, d, vg);
            String shuiHeWu = StatusDetect.isShuiHeWu(reciveCycleData, g);
            qba01.setJy(jiYe)
                    .setDd(shuiHeWu);
        }


        result.addAll(qba01s);


        return CompletableFuture.completedFuture("yes");
    }


    @Override
    public List<String> getJiYeAndDD(Qba01 qba01) {
        double g = 0.6;
        double d = 62;
        double vg = 2.5;
        Timestamp start = DateUtils.stringToDate(DateUtils.sqldateToString(qba01.getRq()) + " 00:00:00");
        Timestamp end = DateUtils.stringToDate(DateUtils.sqldateToString(qba01.getRq()) + " 23:59:59");

        /**
         * 获取天然气相对密度
         */
        QueryWrapper<Qfc01> qfc01QueryWrapper = new QueryWrapper<>();
        qfc01QueryWrapper.eq("JH", qba01.getJh())
                .ge("QYRQ", start)
                .le("QYRQ", end);
        Qfc01 one = qfc01Service.getOne(qfc01QueryWrapper);
        if (one != null && one.getTrqxdmd() != null)
            g = one.getTrqxdmd().doubleValue();


        ReciveCycleData reciveCycleData = new ReciveCycleData()
                .setJkwd(qba01.getJkwd() == null ? 0 : qba01.getJkwd().doubleValue())
                .setTgyl(qba01.getPjty() == null ? 0 : qba01.getPjty().doubleValue())
                .setYgyl(qba01.getPjyy() == null ? 0 : qba01.getPjyy().doubleValue())
                .setWsyl(qba01.getWsyl() == null ? 0 : qba01.getWsyl().doubleValue())
                .setCqill(qba01.getRcql() == null ? 0 : qba01.getRcql().doubleValue());
        String jiYe = StatusDetect.isJiYe(reciveCycleData, g, d, vg);
        String shuiHeWu = StatusDetect.isShuiHeWu(reciveCycleData, g);
        LinkedList<String> strings = new LinkedList<>();
        strings.add(jiYe);
        strings.add(shuiHeWu);
        return strings;
    }


    /**
     * 拿到最新的数据，分页
     *
     * @param page
     * @return
     */
    @Override
    public IPage<Qba01M> getAllLastest(IPage<Qba01M> page, List<String> jhs) {
        IPage allByRq = baseMapper.findAllByRq(page, jhs);
        return allByRq;
    }

    //    获取最新的一条数据
    @Override
    public List<Qba01M> getLastest() {
        List<Qba01M> latest = baseMapper.getLatest();
        return latest;
    }

    @Override
    public List<Qba01Count> countQba01(List<String> ywbhs, List<String> zwbhs, int total, Date start) {
        ConcurrentHashMap<String, Qba01Count> resultMap = new ConcurrentHashMap<>();
        ArrayList<CompletableFuture> completableFutures = new ArrayList<>();
        for (int i = 0; i < total; i += 1000) {
            CompletableFuture<String> stringCompletableFuture = qba01Service2.countQba01ForMultiThread(ywbhs, zwbhs, i, i + 1000, start, resultMap);
            completableFutures.add(stringCompletableFuture);
        }
//      等待所有统计线程完成
        CompletableFuture.allOf(completableFutures.toArray(
                new CompletableFuture[completableFutures.size()]
        )).join();


        ArrayList<Qba01Count> list = new ArrayList(resultMap.values());

        list.sort((a,b)->{
           return  b.getConditions().size()-a.getConditions().size();
        });

//          分页多线程处理
        return list;
    }

    @Override
    public List<Qba01M> getLastest2() {
        return baseMapper.getLatest2();
    }


}
